package com.breezelin.freshmarket.adpaters;

/**
 * Created by Breeze Lin
 * 23:09 2016/5/18
 * 1linyufeng1@gmail.com
 */

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.breezelin.freshmarket.R;
import com.breezelin.freshmarket.entities.data.Category;
import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * 目录列表适配器
 */
public class CategoryAdapter extends BaseAdapter {

	/**
	 * 上下文
	 */
	private Context context;
	/**
	 * 目录信息
	 */
	private List<Category> categories;
	/**
	 * 监听
	 */
	private CategoryListener listener;

	public CategoryAdapter(Context context, List<Category> categories, CategoryListener listener) {
		this.context = context;
		this.categories = categories;
		this.listener = listener;
	}

	@Override
	public int getCount() {
		int size = 0;
		if (categories != null) {
			size = categories.size();
		}
		return size;
	}

	@Override
	public Object getItem(int position) {
		return categories.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Item item = convertView != null ? (Item) convertView.getTag() : new Item(
				LayoutInflater.from(context).inflate(R.layout.item_category, parent, false));
		item.setData(categories.get(position));
		return item.getRootView();
	}

	/**
	 * 目录条目
	 */
	private class Item implements View.OnClickListener {

		/**
		 * 根布局
		 */
		private View rootView;
		/**
		 * 当前目录条目
		 */
		private Category category;
		/**
		 * 图标
		 */
		private ImageView iconImg;
		/**
		 * 标题
		 */
		private TextView titleTxt;
		/**
		 * 描述
		 */
		private TextView descriptionTxt;

		public Item(View rootView) {
			this.rootView = rootView;
			this.rootView.setTag(this);
			iconImg = (ImageView) rootView.findViewById(R.id.icon);
			titleTxt = (TextView) rootView.findViewById(R.id.title);
			descriptionTxt = (TextView) rootView.findViewById(R.id.description);
			rootView.setOnClickListener(this);
		}

		public View getRootView() {
			return rootView;
		}

		/**
		 * 设置条目内容
		 *
		 * @param category 目录信息
		 */
		public void setData(Category category) {
			this.category = category;

			Picasso.with(context).load(category.getSmallIcon()).into(iconImg);
			titleTxt.setText(category.getCategoryName());
			descriptionTxt.setText(category.getDescription());
		}

		@Override
		public void onClick(View v) {
			listener.onCategorySelected(category);
		}
	}

	/**
	 * 目录列表监听
	 */
	public interface CategoryListener {

		/**
		 * 目录点击回调
		 *
		 * @param category 目录信息
		 */
		void onCategorySelected(Category category);
	}
}
